package com.clippick;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.Window;
import co.kr.clippick.R;

import com.clippick.api.ClipPickListener;
import com.clippick.api.GetApi;
import com.clippick.common.GlobalValue;
import com.clippick.common.Toasts;
import com.clippick.common.Utils;
import com.clippick.network.SocketIOClient;

public class IntroActivity extends Activity {
	// common
	private Context mContext;
	private ConnectivityManager manager;
	public static SocketIOClient client;

	// display

	// data:info
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	private String userEmail = "";
	private String userPass = "";

	private final int FLAG_START_MAIN = 0;
	private final int FLAG_START_LOGIN = 1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.intro);

		if (Utils.isAndroidLowerThanICS()) {
			// remove title
			requestWindowFeature(Window.FEATURE_NO_TITLE);
		} else {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		mContext = (Context) this;
		pref = mContext.getSharedPreferences(GlobalValue.KEY,
				Context.MODE_PRIVATE);

		// get the user info from prefs
		if (!pref.getString("userID", "").equals("")) {
			this.userEmail = pref.getString("userID", "");
		}

		if (!pref.getString("userPass", "").equals("")) {
			this.userPass = pref.getString("userPass", "");
		}

		// get instance network connectivity
		manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		// create folder for cache image feeds
		File imageFolder = new File(GlobalValue.CLIPPICK_IMAGE_ROOT_FOLDER);
		imageFolder.mkdirs();

		// time interval 0.5s
		initialize();

		GlobalValue.clearAppClip(mContext);
	}

	/** 0.5s 후에 로그인 시도 */
	private void initialize() {
		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				int start = msg.what;
				switch (start) {
				case 0:
					if (Utils.checkNetwokState(manager)) {
						new LoginTask().execute();
					} else {
						Toasts.showToast(mContext,
								getString(R.string.network_fail));
						startLogin();
					}

					break;

				case 1:
					startLogin();
					break;
				}
			}
		};

		Message startMain = handler.obtainMessage(this.FLAG_START_MAIN);
		Message startLogin = handler.obtainMessage(this.FLAG_START_LOGIN);

		if (pref.getString("userPass", "").equals("")) {
			handler.sendMessageDelayed(startLogin, 500);
			Log.i("user", "email : " + pref.getString("UserID", ""));
			Log.i("user", "password : " + pref.getString("userPass", ""));
		} else {
			handler.sendMessageDelayed(startMain, 500);
		}
	}

	// HTTP Request from thread
	class LoginTask extends AsyncTask<String, String, String> {
		int returnCode = 0;
		String returnMessage = null;
		Map<String, String> response = null;

		@Override
		protected String doInBackground(String... params) {
			GetApi api = new GetApi(mContext);
			response = api.loginApi(userEmail, userPass);
			returnCode = Integer.parseInt(response.get("returnCode"));

			if (returnCode != 200) {
				returnMessage = response.get("returnMessage");
			}

			return null;
		}

		protected void onPostExecute(String unused) {
			switch (returnCode) {
			case 200:
				// store as global variable to access easier
				GlobalValue.USER_ID = userEmail;
				GlobalValue.USER_KEY = pref.getString("REGISTRATION_KEY", "");
				GlobalValue.UPDATE_TIME = response.get("UPDATE_TIME")
						.toString();
				GlobalValue.AppLatestSyncTime = GlobalValue.UPDATE_TIME;
				// GlobalValue.setUpdateTime(mContext,
				// GlobalValue.AppLatestSyncTime);

				startClipPick();
				break;

			default:
				startLogin();
				break;
			}
		}
	}

	private void startLogin() {
		Intent intent = new Intent(mContext, LoginActivity.class);
		startActivity(intent);
		this.overridePendingTransition(R.anim.bottom_to_top,
				R.anim.top_to_bottom);
		finish();
	}

	private void startClipPick() {
		Intent intent = new Intent(mContext, MainActivity.class);
		startActivity(intent);
		this.overridePendingTransition(R.anim.bottom_to_top,
				R.anim.top_to_bottom);
		finish();
	}

	public void onPause() {
		super.onPause();
		int nBackStatus = GlobalValue.getBackgroundOn(this);
		switch (nBackStatus) {
		case GlobalValue.ACT_ON_SERVICE_OFF:
			GlobalValue.saveBackgroundPref(this,
					GlobalValue.ACT_OFF_SERVICE_OFF);
			break;
		case GlobalValue.ACT_ON_SERVICE_ON:
			GlobalValue
					.saveBackgroundPref(this, GlobalValue.ACT_OFF_SERVICE_ON);
			break;
		default:
			break;
		}
	}

	public void onResume() {
		super.onResume();
		int nBackStatus = GlobalValue.getBackgroundOn(this);
		switch (nBackStatus) {
		case GlobalValue.ACT_OFF_SERVICE_OFF:
			GlobalValue
					.saveBackgroundPref(this, GlobalValue.ACT_ON_SERVICE_OFF);
			break;
		case GlobalValue.ACT_OFF_SERVICE_ON:
			GlobalValue.saveBackgroundPref(this, GlobalValue.ACT_ON_SERVICE_ON);
			break;
		default:
			break;
		}
	}
}
